import { defineComponent, onMounted, onUnmounted, reactive } from 'vue'
import axios from 'axios'
import Draw from './draw'

export default defineComponent({
  components: {
    Draw,
  },
  setup() {
    let intervalInstance = null;
    // 预设颜色数组
    const COLOR_LIST = [
      '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272',
      '#fc8452', '#9a60b4', '#ea7ccc', '#51cf66', '#1971c2', '#f59f00'
    ];

    const cdata = reactive({
      seriesData: [] // 格式: [{ name: '科室', value: 数量, itemStyle: { color: '颜色' } }]
    })

    // 获取并处理数据（适配新接口）
    const fetchData = async () => {
      try {
        // 调用新接口地址
        const response = await axios.get(
          window.globalConfig.baseApi + '/api/Nurse/GetAllStatisticsDataGroupJson?IIIDataType=手术人次病区排名&flag=1'
        );
        const apiData = response.data;

        // 处理数据并分配颜色（适配新字段）
        cdata.seriesData = apiData
          .filter(item => Number(item.number) > 0) // 过滤有效数据
          .map((item, index) => ({
            name: item.deptName, // 对应接口的deptName字段
            value: Number(item.number), // 对应接口的number字段（转为数字）
            itemStyle: {
              color: COLOR_LIST[index % COLOR_LIST.length] // 循环分配颜色
            }
          }));

      } catch (error) {
        console.error("获取数据失败:", error);
        cdata.seriesData = [];
      }
    }

    onMounted(() => {
      fetchData();
      // 每10分钟刷新一次数据
      intervalInstance = setInterval(fetchData, 10 * 60 * 1000);
    })

    onUnmounted(() => {
      if (intervalInstance) clearInterval(intervalInstance);
    })

    return () => (
      <div class="chart-container">
        <Draw cdata={cdata} />
      </div>
    );
  },
});